<template>
  <div class="overview-container">
    <Box>
      <div class="profit-overview">
        <h2 class="overview-title">投资总览</h2>
        <div class="profit-stats">
          <div class="stat-item">
            <div class="stat-label-container">
              <div class="stat-label">今日预计盈亏</div>
              <div class="stat-change" :class="todayProfitPercent >= 0 ? 'profit' : 'loss'">
                {{ todayProfitPercent >= 0 ? '+' : '' }}{{ todayProfitPercent.toFixed(2) }}%
              </div>
            </div>
            <div class="stat-value-container">
              <div class="stat-value" :class="totalTodayProfit >= 0 ? 'profit' : 'loss'">
                {{ formatNumber(totalTodayProfit) }}
              </div>
              <div class="stat-unit">元</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-label-container">
              <div class="stat-label">持仓盈亏</div>
              <div class="stat-change" :class="holdingAmountChangePercent >= 0 ? 'profit' : 'loss'">
                {{ holdingAmountChangePercent >= 0 ? '+' : ''
                }}{{ holdingAmountChangePercent.toFixed(2) }}%
              </div>
            </div>
            <div class="stat-value-container">
              <div class="stat-value" :class="totalHoldingProfit >= 0 ? 'profit' : 'loss'">
                {{ formatNumber(totalHoldingProfit) }}
              </div>
              <div class="stat-unit">元</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-label">总持仓金额</div>

            <div class="stat-value-container">
              <div class="stat-value">{{ formatNumber(totalHoldingAmount) }}</div>
              <div class="stat-unit">元</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-label">总投入成本</div>
            <div class="stat-value-container">
              <div class="stat-value">{{ formatNumber(totalInvestmentAmount) }}</div>
              <div class="stat-unit">元</div>
            </div>
          </div>
        </div>
      </div>
    </Box>

    <Box>
      <div class="market-overview">
        <h2 class="overview-title">市场概览</h2>
        <div class="index-section">
          <h3 class="section-title">主要指数</h3>

          <!-- 指数列表 -->
          <div class="index-list">
            <div
              v-for="(index, key) in marketIndices"
              :key="key"
              class="index-item"
              :class="index.trend > 0 ? 'rise' : 'fall'"
              @click="handleIndexClick(index)"
            >
              <div class="index-content">
                <div class="index-info">
                  <div class="index-name">{{ index.name }}</div>
                  <div class="index-code">{{ index.code }}</div>
                </div>
                <div class="index-data">
                  <div
                    class="index-value"
                    :class="index.trend > 0 ? 'rise' : 'fall'"
                    :data-value="index.value"
                  >
                    {{ formatNumber(index.value) }}
                  </div>
                  <div class="index-change" :class="index.trend > 0 ? 'rise' : 'fall'">
                    {{ index.trend > 0 ? '+' : '' }}{{ index.change }}%
                  </div>
                </div>
              </div>

              <!-- 涨跌幅趋势图标 -->
              <div class="trend-icon" :class="index.trend > 0 ? 'rise' : 'fall'">
                <i class="fa" :class="index.trend > 0 ? 'fa-caret-up' : 'fa-caret-down'"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Box>
  </div>
</template>

<script setup lang="ts">
import Box from '@/components/Box/Index.vue'
import { onMounted, ref, computed } from 'vue'
import { queryStockDetailsApi } from '@/api/modules/Rich'
import { ElMessage } from 'element-plus'
import { useProfitStore } from '@/stores/profitStore'

// 从store获取盈亏数据
const profitStore = useProfitStore()

// 计算总的盈亏数据
const totalTodayProfit = computed(() => {
  return (profitStore.fundProfit.todayProfit || 0) + (profitStore.stockProfit.todayProfit || 0)
})

const totalHoldingProfit = computed(() => {
  return (profitStore.fundProfit.holdingProfit || 0) + (profitStore.stockProfit.holdingProfit || 0)
})

const totalHoldingAmount = computed(() => {
  return (
    (profitStore.fundProfit.totalHoldingAmount || 0) +
    (profitStore.stockProfit.totalHoldingAmount || 0)
  )
})

const totalInvestmentAmount = computed(() => {
  return (
    (profitStore.fundProfit.totalInvestmentAmount || 0) +
    (profitStore.stockProfit.totalInvestmentAmount || 0)
  )
})

// 计算总持仓金额相较于成本的百分比变化
const holdingAmountChangePercent = computed(() => {
  const cost = totalInvestmentAmount.value
  if (cost === 0) return 0
  return ((totalHoldingAmount.value - cost) / cost) * 100
})

// 计算今日盈亏相较于总持仓金额的百分比变化
const todayProfitPercent = computed(() => {
  const amount = totalHoldingAmount.value
  if (amount === 0) return 0
  return (totalTodayProfit.value / amount) * 100
})

// 定义指数数据类型接口
interface MarketIndex {
  name: string
  code: string
  secid: string
  value: number
  change: number
  trend: 1 | -1
}

// 市场指数初始数据
const marketIndices = ref<MarketIndex[]>([
  {
    name: '上证指数',
    code: '000001',
    secid: '1.000001',
    value: 0,
    change: 0,
    trend: 1,
  },
  {
    name: '深证成指',
    code: '399001',
    secid: '0.399001',
    value: 0,
    change: 0,
    trend: 1,
  },
  {
    name: '创业板指',
    code: '399006',
    secid: '0.399006',
    value: 0,
    change: 0,
    trend: -1,
  },
  { name: '科创50', code: '000688', secid: '1.000688', value: 0, change: 0, trend: -1 },
])

// 移除加载和错误状态相关的ref定义
// const loading = ref<boolean>(false)
// const error = ref<boolean>(false)
// const errorMessage = ref<string>('')

// 股票字段常量
const STOCK_FIELDS =
  'f59,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292'

/**
 * 格式化数字显示，保留两位小数并添加千位分隔符
 * @param num 要格式化的数字
 * @returns 格式化后的字符串
 */
const formatNumber = (num: number): string => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })
}

/**
 * 获取单个指数的详细数据
 * @param secid 指数的secid
 * @returns 包含当前价、涨跌幅等信息的对象
 */
const fetchIndexDetails = async (secid: string) => {
  try {
    const { data } = await queryStockDetailsApi({ secid, fields: STOCK_FIELDS })
    const currentPrice = data.f43 / 100 // 当前价
    const preClose = data.f60 / 100 // 昨收价

    // 计算涨跌幅
    const change = currentPrice - preClose
    const changePercent = ((change / preClose) * 100).toFixed(2)

    return {
      currentPrice,
      change: parseFloat(changePercent),
      trend: change > 0 ? 1 : -1,
    }
  } catch (err) {
    console.error(`获取指数${secid}数据失败:`, err)
    throw new Error(`获取指数数据失败`)
  }
}

/**
 * 批量获取所有指数的数据并更新
 */
const fetchAllIndices = async () => {
  // 移除加载状态设置
  // loading.value = true
  // error.value = false
  // errorMessage.value = ''

  try {
    // 逐个获取每个指数的数据
    const updatedIndices = await Promise.all(
      marketIndices.value.map(async (index) => {
        const details = await fetchIndexDetails(index.secid)
        return {
          ...index,
          value: details.currentPrice,
          change: details.change,
          trend: details.trend as 1 | -1,
        }
      }),
    )

    // 更新指数数据
    marketIndices.value = updatedIndices
    // ElMessage.success('指数数据更新成功')
  } catch (err) {
    // 移除错误状态设置，仅保留消息提示
    ElMessage.error(err instanceof Error ? err.message : '获取指数数据时发生未知错误')
  } finally {
    // 移除加载状态清除
    // loading.value = false
  }
}

/**
 * 处理指数项点击事件
 * @param index 被点击的指数对象
 */
const handleIndexClick = (index: MarketIndex) => {
  ElMessage.info(`查看${index.name}(${index.code})的详细信息`)
  console.log('指数点击:', index)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAllIndices()

  // 定时刷新数据，每5分钟刷新一次
  const refreshInterval = setInterval(fetchAllIndices, 1 * 5000)

  // 组件卸载时清除定时器
  return () => clearInterval(refreshInterval)
})
</script>

<style lang="scss" scoped>
// 基础变量
$primary-color: #409eff;
$success-color: #67c23a;
$danger-color: #f56c6c;
$warning-color: #e6a23c;
$text-primary: #303133;
$text-secondary: #606266;
$text-placeholder: #909399;
$bg-color: #f5f7fa;
$card-bg: #ffffff;
$border-radius: 12px;
$shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
$transition: all 0.3s ease;

.overview-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 20px;
}

.profit-overview {
  padding: 24px;
  background-color: $card-bg;
  border-radius: $border-radius;
  box-shadow: $shadow;
}

.overview-title {
  font-size: 18px;
  font-weight: 600;
  color: $text-primary;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.profit-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 24px;
  background-color: $bg-color;
  border-radius: $border-radius;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: $transition;
  height: 100%;
  min-height: 120px;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
  }
}

.stat-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.stat-label-container {
  display: flex;
  justify-content: space-between;
}

.stat-label {
  text-align: left;
  font-size: 18px;
  color: $text-secondary;
  font-weight: 500;
}

.stat-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(64, 158, 255, 0.1);
  color: $primary-color;
}

.stat-value-container {
  width: 100%;
  display: flex;
  align-items: baseline;
  justify-content: flex-end;
  gap: 4px;
  margin: 8px 0;
}

.stat-value {
  font-size: 26px;
  font-weight: 700;
  color: $text-primary;
  line-height: 1.2;
  transition: $transition;
  letter-spacing: -0.5px;
}

.stat-unit {
  font-size: 12px;
  color: $text-placeholder;
  padding-top: 2px;
}

.stat-change {
  font-size: 18px;
  padding: 2px 8px;
  border-radius: 12px;
  background-color: rgba(103, 194, 58, 0.1);
  color: $success-color;
  align-self: flex-start;
}

.stat-change.profit {
  background-color: rgba(245, 108, 108, 0.1);
  color: $danger-color;
}

.stat-change.loss {
  background-color: rgba(103, 194, 58, 0.1);
  color: $success-color;
}

.profit {
  color: $danger-color;
}

.loss {
  color: $success-color;
}

// 响应式调整
@media screen and (max-width: 992px) {
  .profit-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 576px) {
  .profit-stats {
    grid-template-columns: 1fr;
  }

  .stat-item {
    padding: 20px 16px;
  }

  .stat-value {
    font-size: 20px;
  }
}

.overview-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profit-overview {
  padding: 20px;
}

.profit-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 15px;
}

.profit {
  color: #f56c6c;
}

.loss {
  color: #67c23a;
}

.overview-container {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.market-overview {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.overview-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1e293b;
  position: relative;
  padding-left: 8px;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 16px;
    background-color: #3b82f6;
    border-radius: 3px;
  }
}

.index-section {
  margin-top: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #475569;
  display: flex;
  align-items: center;

  &::after {
    content: '';
    flex: 1;
    height: 1px;
    background-color: #e2e8f0;
    margin-left: 12px;
  }
}

.index-list {
  display: flex;
  gap: 16px;
  width: 100%;
  overflow: hidden;
  flex-wrap: wrap; // 适配小屏幕
}

.index-item {
  flex: 1;
  min-width: 220px; // 确保在小屏幕上有合适的宽度
  border: 2px solid #e5e7eb;
  border-left-width: 3px; // 左侧边框加宽
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;

  &:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
    border-color: #dbeafe;
  }

  // 上涨状态的左侧边框颜色
  &.rise {
    border-left-color: #ef4444;
  }

  // 下跌状态的左侧边框颜色
  &.fall {
    border-left-color: #22c55e;
  }
}

.index-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.index-info {
  display: flex;
  flex-direction: column;
}

.index-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #1e293b;
  font-size: 15px;
}

.index-code {
  font-size: 12px;
  color: #6b7280;
}

.index-data {
  text-align: right;
}

.index-value {
  font-weight: 500;
  margin-bottom: 4px;
  font-size: 15px;
  transition: color 0.3s ease;
}

.index-change {
  font-size: 12px;
  transition: color 0.3s ease;
}

.trend-icon {
  position: absolute;
  top: 12px;
  right: 12px;
  opacity: 0.7;
  transition: opacity 0.3s ease;

  .index-item:hover & {
    opacity: 1;
  }
}

.rise {
  color: #ef4444; /* 上涨红色 */
}

.fall {
  color: #22c55e; /* 下跌绿色 */
}

// 移除加载和错误状态相关样式
// 加载状态样式
// .loading-state {
//   display: flex;
//   flex-direction: column;
//   align-items: center;
//   justify-content: center;
//   padding: 40px 0;
//   color: #64748b;

//   .spinner {
//     width: 24px;
//     height: 24px;
//     border: 3px solid #e2e8f0;
//     border-top-color: #3b82f6;
//     border-radius: 50%;
//     animation: spin 1s linear infinite;
//     margin-bottom: 12px;
//   }
// }

// // 错误状态样式
// .error-state {
//   display: flex;
//   flex-direction: column;
//   align-items: center;
//   justify-content: center;
//   padding: 40px 0;
//   color: #dc2626;

//   i {
//     font-size: 24px;
//     margin-bottom: 12px;
//   }

//   .retry-btn {
//     margin-top: 16px;
//     padding: 6px 12px;
//     background-color: #3b82f6;
//     color: white;
//     border: none;
//     border-radius: 4px;
//     cursor: pointer;
//     transition: background-color 0.2s ease;

//     &:hover {
//       background-color: #2563eb;
//     }
//   }
// }

// // 加载动画
// @keyframes spin {
//   to {
//     transform: rotate(360deg);
//   }
// }

// 响应式调整
@media (max-width: 768px) {
  .overview-container {
    padding: 12px;
  }

  .market-overview {
    padding: 16px;
  }

  .index-list {
    gap: 12px;
  }

  .index-item {
    padding: 12px;
    min-width: 160px;
  }
}
</style>
